package com.ctgu.chatapp.view.fragment.MainFragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.ctgu.chatapp.databinding.FragmentSelfInfoBinding
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.model.Retrofit.IMSServiceImpl
import com.ctgu.chatapp.view.adapter.PhotoWallAdapter
import com.ctgu.chatapp.viewModel.MainViewModel
import com.mx.imgpicker.builder.MXPickerBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class SelfInformation : Fragment() {

    lateinit var binding: FragmentSelfInfoBinding

    val viewModel by lazy { ViewModelProvider(requireActivity())[MainViewModel::class.java] }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentSelfInfoBinding.inflate(inflater, container, false)
        binding.viewModel = viewModel
        binding.lifecycleOwner = requireActivity()
        imagePicker()
        initAdapter()
        return binding.root
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0x22 && data != null) {
            val paths = MXPickerBuilder.getPickerResult(data)
            CoroutineScope(IO).launch {
                val body: RequestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart(
                        "avatar",
                        paths[0],
                        RequestBody.create(
                            MediaType.parse("application/octet-stream"),
                            File(paths[0])
                        )
                    )
                    .addFormDataPart("chatId", viewModel.user.value!!.chatID.toString())
                    .build()
                val result = IMSServiceImpl.imsServiceImpl.service.uploadImage(body)
                DataBaseManager.getInstance(requireContext()).getInformationDao()
                    .updateProfile(result, viewModel.user.value!!.chatID.toInt())
            }
        }
    }

    private fun imagePicker() {
        binding.profileBack.setOnClickListener {
            val intent = MXPickerBuilder().setMaxSize(1).createIntent(requireContext())
            startActivityForResult(intent, 0x22, null)
        }
    }

    private fun initAdapter() {
        val adapter = PhotoWallAdapter(listOf())
    }


}